﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using RoyTools.D3Monitor.FormUI.Properties;

namespace RoyTools.D3Monitor.FormUI.Helper
{
    /// <summary>
    /// 配置辅助类
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private static string ConfigFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\Config.xml";

        /// <summary>
        /// 读取配置
        /// </summary>
        /// <returns></returns>
        public static string LoadConfig()
        {
            if (File.Exists(ConfigFilePath))
            {
                try
                {
                    var serializer = new XmlSerializer(typeof(Config));
                    using (var fileStream = new FileStream(ConfigFilePath, FileMode.Open))
                    {
                        Program.Config = serializer.Deserialize(fileStream) as Config;
                        fileStream.Close();
                        fileStream.Dispose();
                    }
                }
                catch
                {
                    return Resources.ConfigFileLoadError;
                }
            }
            else
            {
                Program.Config = new Config();
                Program.Config.LogMonitorSettings = new List<LogMonitorSetting>();
                Program.Config.MailSetting = new MailSetting();
                SaveConfig();
            }
            return string.Empty;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public static void SaveConfig()
        {
            var serializer = new XmlSerializer(typeof(Config));
            using (var memoryStream = new MemoryStream())
            {
                serializer.Serialize(memoryStream, Program.Config);
                memoryStream.Seek(0, SeekOrigin.Begin);
                using (var streamReader = new StreamReader(memoryStream))
                {
                    var xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(streamReader.ReadToEnd());
                    xmlDocument.Save(ConfigFilePath);
                    streamReader.Close();
                    streamReader.Dispose();
                }
                memoryStream.Close();
                memoryStream.Dispose();
            }
        }
    }
}
